package cn.xing.modules.app.service.impl;

import cn.xing.common.utils.PageUtils;
import cn.xing.common.utils.Query;
import cn.xing.modules.app.dao.DeliveryLogDao;
import cn.xing.modules.app.entity.DeliveryLogEntity;
import cn.xing.modules.app.service.DeliveryLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("deliveryLogService")
public class DeliveryLogServiceImpl extends ServiceImpl<DeliveryLogDao, DeliveryLogEntity> implements DeliveryLogService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");

        IPage<DeliveryLogEntity> page = this.page(
                new Query<DeliveryLogEntity>().getPage(params),
                new QueryWrapper<DeliveryLogEntity>()
                        .orderByDesc("delivery_start_time")
                        .eq(StringUtils.isNotEmpty(key), "order_sn", key)

        );

        return new PageUtils(page);
    }

    @Override
    public void start(String orderSn) {
        DeliveryLogEntity deliveryLogEntity = queryByOrderSn(orderSn);
        if (deliveryLogEntity == null) {
            deliveryLogEntity = new DeliveryLogEntity();
            deliveryLogEntity.setOrderSn(orderSn);
        }

        deliveryLogEntity.setDeliveryStartTime(new Date());

        saveOrUpdate(deliveryLogEntity);
    }

    @Override
    public void sended(String orderSn) {
        DeliveryLogEntity deliveryLogEntity = queryByOrderSn(orderSn);
        if (deliveryLogEntity == null) {
            deliveryLogEntity = new DeliveryLogEntity();
            deliveryLogEntity.setOrderSn(orderSn);
        }

        deliveryLogEntity.setDeliveryEndTime(new Date());

        saveOrUpdate(deliveryLogEntity);
    }

    public DeliveryLogEntity queryByOrderSn(String orderSn) {
        return this.baseMapper.selectOne(new QueryWrapper<DeliveryLogEntity>().eq("order_sn", orderSn));
    }
}